package net.lzzy.practices.web.courses;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstant;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.Chapter;
import net.lzzy.practices.entities.Course;
import net.lzzy.practices.service.ChapterService;
import net.lzzy.practices.service.CourseService;
import net.lzzy.practices.utils.JwtUtil;
import net.lzzy.practices.utils.StringUtil;
import net.lzzy.practices.web.models.ApiResult;

import net.lzzy.practices.web.models.ChapterInfo;
import net.lzzy.practices.web.models.ChapterKeyInfo;
import net.lzzy.practices.web.models.VmChapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author AndyStern
 */
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_CHAPTER_ROOT)
@Api(tags = "章节相关业务")
public class ChapterApiController {
    private final ChapterService chService;
    private final CourseService coService;

    public ChapterApiController(ChapterService chService, CourseService coService) {
        this.chService = chService;
        this.coService = coService;
    }


    @ApiOperation("教师获取自己某一个课程所有的章节")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "操作人令牌", dataType = "String", dataTypeClass = JwtUtil.class,
                    paramType = "query", required = true),
            @ApiImplicitParam(name = "id",value = "课程id",dataType = "UUID",dataTypeClass = Course.class,
                    paramType = "query",required = true)
    })
    @GetMapping(ApiConstant.ROUTE_CHAPTER_TEACHER_CHAPTERS)
    public ApiResult getTeachersChapters(@RequestParam String token, @RequestParam UUID courseId) {
        List<VmChapter> chapters = new ArrayList<>();
        chService.getTeachersChapters(courseId, token).forEach(chapter -> chapters.add(VmChapter.create(chapter)));
        return new ApiResult(true, chapters.size() + "", chapters);
    }

    @ApiOperation("学生获取所有开放的章节")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "操作人令牌", dataType = "String", dataTypeClass = JwtUtil.class,
                    paramType = "query", required = true),
            @ApiImplicitParam(name = "courseId",value = "课程id",dataType = "UUID",dataTypeClass = Course.class,
                    paramType = "query",required = true),
            @ApiImplicitParam(name = "studentId",value = "学生id",dataType = "UUID",dataTypeClass = Course.class,
                    paramType = "query",required = true)
    })
    @GetMapping(ApiConstant.ROUTE_CHAPTER_STUDENT_CHAPTERS)
    public ApiResult getStudentChapters(@RequestParam String token,@RequestParam UUID courseId,@RequestParam UUID studentId){
        List<VmChapter> chapters = new ArrayList<>();
        chService.getStudentsChapters(studentId,courseId,token).forEach(chapter -> chapters.add(VmChapter.create(chapter)));
        return new ApiResult(true,chapters.size()+"",chapters);
    }





    private ApiResult addOrUpdate(ChapterInfo info, UUID id) {
        String token = info.getToken();
        String name = info.getName();
        String description = info.getDescription();
        boolean open = info.isOpen();
        String courseId = info.getCid();
        if (StringUtil.isEmpty(name) ||
                StringUtil.isEmpty(description) ||
                StringUtil.isEmpty(courseId)) {
            return new ApiResult(false, Messages.MISS_ARGS.toString(), null);
        }
        Course course = coService.getById(UUID.fromString(courseId));
        if (course == null) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), null);
        }
        Chapter chapter;
        boolean add = id == null;
        if (add) {
            chapter = new Chapter();
            chapter.setCourse(course);
        } else {
            chapter = chService.getById(id);
            if (chapter == null) {
                return new ApiResult(false, Messages.WRONG_ID.toString(), null);
            }
        }
        chapter.setUpdateTime(new Date());
        chapter.setOpen(open);
        chapter.setName(name);
        chapter.setDescription(description);
        if (add) {
            return new ApiResult(true, Messages.SUCCESS.toString(), VmChapter.create(chService.add(chapter)));
        } else {
            Chapter updated = chService.update(chapter, token);
            if (updated == null) {
                return new ApiResult(false, Messages.NO_PERMISSION.toString(), null);
            }
            return new ApiResult(true, Messages.SUCCESS.toString(), VmChapter.create(updated));
        }
    }

    @ApiOperation("添加章节")
    @ApiImplicitParam(name = "info",value = "操作令牌token,章节id,章节的开放/关闭",dataType = "ChapterInfo",dataTypeClass = ChapterInfo.class,
            paramType = "body",required = true)
    @PostMapping(ApiConstant.ROUTE_CHAPTER_ADD)
    public ApiResult add(@RequestBody ChapterInfo info) {
        return addOrUpdate(info, null);
    }

    @ApiOperation("更新章节")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "info",value = "操作令牌token,章节id,章节的开放/关闭",dataType = "ChapterInfo",dataTypeClass = ChapterInfo.class,
                    paramType = "body",required = true),
            @ApiImplicitParam(name = "id",value = "章节id",dataType = "UUID",dataTypeClass = Chapter.class,
                    paramType = "query",required = true),
    })
    @PostMapping(ApiConstant.ROUTE_CHAPTER_UPDATE)
    public ApiResult update(@RequestBody ChapterInfo info,@RequestParam UUID id){
        return addOrUpdate(info,id);
    }

    @ApiOperation("章节的开放/关闭")
    @ApiImplicitParam(name = "info",value = "操作令牌token,章节id,章节的开放/关闭",dataType = "ChapterInfo",dataTypeClass = ChapterInfo.class,
            paramType = "body",required = true)
    @PostMapping(ApiConstant.ROUTE_CHAPTER_OPEN_CLOSE)
    public ApiResult openClose(@RequestBody ChapterInfo info){
        String token = info.getToken();
        String strChapterId = info.getCid();
        boolean open = info.isOpen();
        if(StringUtil.isEmpty(token) || StringUtil.isEmpty(strChapterId) ){
            return new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        Chapter chapter = chService.openCloseChapter( open,UUID.fromString(strChapterId),token);
        if(chapter == null){
            return new ApiResult(false,Messages.NO_PERMISSION.toString(), null);
        }
        return new ApiResult(true,Messages.SUCCESS.toString(), VmChapter.create(chapter));
    }

    @ApiOperation("删除课程的一个章节")
    @ApiImplicitParam(name = "info",value = "课程id,章节id,操作令牌token",dataType = "ChapterKeyInfo",dataTypeClass = ChapterKeyInfo.class,
            paramType = "body",required = true)
    @DeleteMapping(ApiConstant.ROUTE_CHAPTER_REMOVE)
    public ApiResult delete(@RequestBody ChapterKeyInfo info){
        String strChapterId = info.getChapterId();
        String strCourseId = info.getCourseId();
        String token = info.getToken();
        if(StringUtil.isEmpty(token) || StringUtil.isEmpty(strChapterId) || StringUtil.isEmpty(strCourseId)){
            return new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        try {

            UUID chapterId = UUID.fromString(strChapterId);
            UUID courseId = UUID.fromString(strCourseId);
            Messages msg = chService.remove(courseId,chapterId,token);
            return new ApiResult(msg == Messages.SUCCESS, msg.toString(), null);
        }catch (IllegalFormatException e){
            System.out.println(1);
            return new ApiResult(false,Messages.WRONG_ID.toString(), null);
        }

    }
}
